<template>
  <el-container
    direction="vertical"
    style="min-height: 100%; background-color: #f6f6f6"
  >
    <el-affix>
      <MainHeader
        @searchInfoChange="handleSearchInfoChange"
        :search-type="currentTab"
      />
    </el-affix>

    <el-container class="main-container">
      <el-affix target=".main-container" :offset="61" z-index="30">
        <el-aside>
          <MainAside ref="asideComp" />
        </el-aside>
      </el-affix>
      <el-container style="width: 750px">
        <el-main>
          <el-card>
            <el-tabs
              v-model="currentTab"
              class="question-wrapper"
              @tab-change="tabChange"
            >
              <el-tab-pane label="问题" name="question" />
              <el-tab-pane label="用户" name="user" />
            </el-tabs>
            <el-skeleton :loading="searchLoading" animated>
              <template #template>
                <div style="display: flex; flex-direction: column; gap: 10px">
                  <el-skeleton-item variant="h3" style="width: 25%" />
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" />
                  <el-skeleton-item variant="text" style="width: 60%" />
                </div>
              </template>
              <template #default>
                <el-empty
                  v-if="items == null || items.length === 0"
                  description="没有搜索到任何结果"
                />
                <div
                  class="question-box"
                  v-for="(question, index) in items"
                  :key="index"
                  v-else-if="currentTab === 'question'"
                >
                  <el-divider v-if="index > 0" />
                  <div class="question-content">
                    <h3
                      style="cursor: pointer"
                      @click="toQuestionDetail(question)"
                    >
                      {{ question.question_title }}
                    </h3>
                    <el-text truncated>{{ question.question_content }}</el-text>
                  </div>
                  <div class="question-info">
                    <el-button type="primary" :icon="Star" @click="">
                      好问题 {{ question.liked_count }}
                    </el-button>
                    <el-text type="info" style="margin-left: 15px">{{
                      question.create_time
                    }}</el-text>
                  </div>
                </div>
                <div class="user-box" v-for="(user, index) in items" v-else>
                  <el-divider v-if="index > 0" />
                  <div class="user-content">
                    <div style="display: flex; gap: 15px; align-items: center">
                      <el-avatar
                        style="cursor: pointer"
                        @click="asideComp.toUser(user.id)"
                        :src="
                          avatarError
                            ? `//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/default?t=${Math.random().toString(
                                36
                              )}`
                            : `//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/${userId}?t=${Math.random().toString(
                                36
                              )}`
                        "
                        @error="avatarError = !avatarError"
                      />
                      <h3
                        style="cursor: pointer"
                        @click="asideComp.toUser(user.id)"
                      >
                        {{ user.username }}
                      </h3>
                    </div>
                    <el-button
                      :type="user.followed ? 'info' : 'primary'"
                      :icon="Plus"
                      @click="asideComp.followUser(user)"
                    >
                      {{ user.followed ? "已关注" : "关注" }}
                    </el-button>
                  </div>
                  <!--                <div>-->
                  <!--                  <el-text size="large">-->
                  <!--                    粉丝: {{ user.followed_count }}-->
                  <!--                  </el-text>-->
                  <!--                </div>-->
                </div>
              </template>
            </el-skeleton>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script setup>
import MainHeader from "@/components/common/MainHeader.vue";
import MainAside from "@/components/common/MainAside.vue";
import { ref } from "vue";
import axios from "axios";
import { Star, Plus } from "@element-plus/icons-vue";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";

const userId = JSON.parse(localStorage.getItem("user")).id;
const asideComp = ref(null);

const currentTab = ref("question"),
  avatarError = ref(false),
  router = useRouter(),
  query = router.currentRoute.value.query;

const searchLoading = ref(true),
  items = ref([]);

handleSearchInfoChange(query);

if (query.type !== currentTab.value) currentTab.value = query.type;

const tabChange = () => {
  searchLoading.value = true;
  router.push({
    path: "/searchPage",
    query: {
      keyword: query.keyword,
      type: currentTab.value,
    },
  });
};

const toQuestionDetail = (question) => {
  let page = router.resolve({
    path: "/QuestionDetail",
    query: {
      question_id: question.question_id,
    },
  });
  window.open(page.href, "_blank");
};

function handleSearchInfoChange(query) {
  switch (query.type) {
    case "question": {
      axios
        .get(
          `http://localhost:8080/question/keyword?keyword=${query.keyword}&current_id=${userId}`
        )
        .then((r) => {
          searchLoading.value = false;
          const resp = r.data;
          if (resp.status === 0) {
            items.value = resp.data;
          } else {
            ElNotification.error("搜索失败，请检查网络连接是否正常");
          }
        })
        .catch((error) => {
          console.log(error.request);
          ElNotification.error("搜索失败，请检查网络连接是否正常");
        });
      break;
    }
    case "user": {
      axios
        .get(
          `http://localhost:8080/user/keyword?keyword=${query.keyword}&user_id=${userId}`
        )
        .then((r) => {
          searchLoading.value = false;
          const resp = r.data;
          if (resp.status === 0) {
            items.value = resp.data;
          } else {
            ElNotification.error("搜索失败，请检查网络连接是否正常");
          }
        })
        .catch((error) => {
          console.log(error.request);
          ElNotification.error("搜索失败，请检查网络连接是否正常");
        });
      break;
    }
  }
}
</script>

<style scoped>
.main-container {
  width: 1100px;
  margin: auto;
}
.user-box,
.question-box {
  text-align: left;
}
.user-content,
.question-content {
  margin-bottom: 15px;
}
.user-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
